import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const _this = Vue.prototype;
let lifeData = {};

/**
 * uniapp - vuex v.1.0.0
 * */

try{
	// 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
	lifeData = uni.getStorageSync('lifeData');
}catch(e){
	
}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = ['token', 'userInfo',"store_id","goodsCarNum","goodsInfo","makeTech","makeStore_id",
"makeDays","makeTime","makeStoreInfo","defaultAddress","makeName","makePhone","makeNum","makeProject","chioseProjects",
"remarks","toStore","toStore_id","rewardInfo","share_user_id","share_goods_id","share_project_id","share_user_id_project",
"fid", "cid", "sid", "userLocationStore", "isRecommend", "is_single"
];

// 保存变量到本地存储中
const saveLifeData = function(key, value){
	// 判断变量名是否在需要存储的数组中
	if(saveStateKeys.indexOf(key) != -1) {
		// 获取本地存储的lifeData对象，将变量添加到对象中
		let tmp = uni.getStorageSync('lifeData');
		// 第一次打开APP，不存在lifeData变量，故放一个{}空对象
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		// 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
		
		uni.setStorageSync('lifeData', tmp);
	}
}
const store = new Vuex.Store({
	state:Object.assign({
		share_user_id_project:'',
		share_goods_id:'',
		share_project_id:'',
		share_user_id:'',
		fid: '',
		cid: '',
		sid: '',
		userLocationStore: [],
		isRecommend: "",
		is_single: 0,
		currentLocation:{},
		isAuth:false,
		rewardInfo:{},//打赏信息
		toStore:'',//自提门店
		toStore_id:'',
		firstHttp:true,
		remarks:'',//备注
		makeProject:[],//默认预约项目
		chioseProjects:[],//选择的预约项目
		makeName:"",//预约姓名
		makePhone:"",//预约手机号
		makeNum:0,//预约的人数
		defaultAddress:{},//默认门店
		makeStoreInfo:{},//预约门店信息
		makeDays:'',//预约日期
		makeTime:'',//预约时间
		makeTech:[],//预约技师
		makeStore_id:1,//预约门店
		token:'',
		store_id:'',
		goodsCarNum:'',
		goodsInfo:{},
		userInfo:{
			avatar:'https://willmid-img.oss-cn-shanghai.aliyuncs.com/2021/09/14/user.jpg',
			username:'点击登录',
			phone:"",
			integral:0,
			balance:0,
		},
		vuex_tabbar: []
	},lifeData),
	mutations: {
		$uStore(state, payload) {
			// 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if(len >= 2) {
				let obj = state[nameArr[0]];
				for(let i = 1; i < len - 1; i ++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				// 单层级变量，在state就是一个普通变量的情况
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			// 保存变量到本地，见顶部函数定义
			saveLifeData(saveKey, state[saveKey])
		}
	},
	actions:{
		//更新用户信息
		async getUserInfo(context){
			console.log(context.state,'context.token');
			if(context.state.token){
				let {code,data} = await _this.$u.api.userInfo();
				if(code){
					context.commit('$uStore', { name:'userInfo',value:data });
					if(!data.phone){
						_this.utlis.goUrl('/pages/mine/index')
					}
				}
			}
		},
		//绑定手机号
		getPhoneNumber(context,e){
			uni.showLoading()
			let {iv,encryptedData} = e.detail;
			uni.login({
				provider: 'weixin',
				success:async (res)=>{
					let {code,msg,data} = await _this.$u.api.bindPhone({code:res.code,iv,encryptedData});
					uni.hideLoading()
					if(code==10000){
						context.commit('$uStore', {name:'token',value:data.user_token})
						context.commit('$uStore', {name:'userInfo',value:data.user})
						_this.$u.toast('登录成功!')
					}
				},
				fail() {
					uni.hideLoading()
				}
			})
		}
	}
})

export default store
